package com.yuyou.train.user.controller;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;  import org.slf4j.LoggerFactory;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.yuyou.train.service.api.lesson.dto.UserClassDTO;
import com.yuyou.train.service.api.lesson.dto.UserLessonTreeDTO;
import com.yuyou.train.service.api.user.dto.UserPageDTO;
import com.yuyou.train.service.api.user.entity.User;
import com.yuyou.train.user.service.IUserDataConfigService;
import com.yuyou.train.user.service.IUserLessonProgressService;
import com.yuyou.train.user.service.IUserService;
import com.yuyou.train.user.vo.req.ReqBehavior;
import com.yuyou.train.user.vo.resp.RespGetLessonContent;
import com.yuyou.train.user.vo.resp.RespNextLessonContent;
import com.yuyou.train.util.bean.LoginRedisObj;
import com.yuyou.train.util.bean.PageParams;
import com.yuyou.train.util.bean.Pagination;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.bean.ReturnResult;
import com.yuyou.train.util.enums.CommEnums;
import com.yuyou.train.util.enums.user.UserEnums;

@Validated
@RestController
@RequestMapping(value="/api/userLesson")
public class UserLessonController extends BaseController{

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private IUserLessonProgressService userLesProService;
	
	@Autowired
	private IUserDataConfigService userDataConfigService;
	
	@Autowired
	private IUserService userService;
		
	
	@ApiOperation(value="班级详情(前台)")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId", value = "用户ID(为空则取登录用户ID)", paramType="query", required = false),
		@ApiImplicitParam(name = "classId", value = "班级ID(为空则取登录班级ID)", paramType="query", required = false)}
		)
	@RequestMapping(value="/getUserClass",method=RequestMethod.POST)
	public ReturnResult<UserClassDTO> getUserClass(
			HttpServletRequest request,
			String classId,
			String userId
			) throws Exception{	
		if(StringUtils.isEmpty(userId)){
			LoginRedisObj loginRedisObj=this.getUserObj(request);
			userId=loginRedisObj.getUserId();
		}
		if(StringUtils.isEmpty(classId)){
			LoginRedisObj loginRedisObj=this.getUserObj(request);
			userId=loginRedisObj.getUserId();
			User user=userService.selectByPrimaryKey(userId);	
			classId=user.getClassId();
		}				
		ResBoolSimpleInfo<UserClassDTO> res=userLesProService.getUserClass(classId, userId);
		return ReturnResult.success(res);
	}
	
	@ApiOperation(value="课程树(前台)")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId", value = "用户ID(为空则取登录用户ID)", paramType="query", required = false)}
		)
	@RequestMapping(value="/getUserLessonTree",method=RequestMethod.POST)
	public ReturnResult<List<UserLessonTreeDTO>> getUserLessonTree(
			HttpServletRequest request,
			String userId
			) throws Exception{	
		if(StringUtils.isEmpty(userId)){
			LoginRedisObj loginRedisObj=this.getUserObj(request);
			userId=loginRedisObj.getUserId();
		}
		User user=userService.selectByPrimaryKey(userId);	
		List<UserLessonTreeDTO> res=userLesProService.getUserLessonTree(user.getClassId(),userId);			
		return ReturnResult.success(res);
	}
	
	
	@ApiOperation(value="课程树节点详细内容(前台)")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "lessonId", value = "课程ID", paramType="query", required = true),
		@ApiImplicitParam(name = "userId", value = "用户ID", paramType="query", required = false),
		@ApiImplicitParam(name = "foreignId", value = "业务ID(感想为感想ID，作业为作业ID)", paramType="query", required = false)}
		)
	@RequestMapping(value="/getLessonContent",method={RequestMethod.POST,RequestMethod.GET})
	public ReturnResult<ResBoolSimpleInfo<RespGetLessonContent>> getLessonContent(
			HttpServletRequest request,
			@NotEmpty (message="lessonId不能为空") String lessonId,
			String userId,
			String foreignId) throws Exception{	
		
		LoginRedisObj loginRedisObj=this.getUserObj(request);
		if(StringUtils.isEmpty(userId)){
			userId=loginRedisObj.getUserId();			
		}
		String loginUserId=loginRedisObj.getUserId();				
		ResBoolSimpleInfo<RespGetLessonContent> resp=userLesProService.getLessonContent(userId,loginUserId, lessonId,foreignId);
		return ReturnResult.success(resp);
	}
	
	@ApiOperation(value="(前台)开启下一个课程(前台)")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "behavior", value = "用户具体行为,格式（{\"end\":{\"content\":\"string\",\"star\":1},\"exam\":{\"examTime\":0,\"myAns\":[{\"ansList\":[\"string\"],\"questionId\":\"string\",\"sort\":0}],\"repeatExam\":true},\"file\":{},\"hwJustCommit\":{\"fileSourceName\":\"string\",\"userFileName\":\"string\",\"userFileUrl\":\"string\"},\"hwNeedComment\":{\"badList\":[\"string\"],\"fileSourceName\":\"string\",\"goodList\":[\"string\"],\"userFileName\":\"string\",\"userFileUrl\":\"string\"},\"music\":{\"duration\":0},\"thought\":{\"learnContent\":\"string\",\"planContent\":\"string\",\"thinkContent\":\"string\",\"title\":\"string\"},\"video\":{\"duration\":0}}）", paramType="query", required = true)}
		)
	@RequestMapping(value="/openUserNextLesson",method=RequestMethod.POST)
	public ReturnResult<ResBoolSimpleInfo<RespNextLessonContent>> openUserNextLesson(
			HttpServletRequest request,
			String behavior) throws Exception{	
		ReqBehavior reqBehavior=JSON.parseObject(behavior,ReqBehavior.class);
		LoginRedisObj loginRedisObj=this.getUserObj(request);	
		ResBoolSimpleInfo<RespNextLessonContent> res=userLesProService.openUserNextLessonLock(loginRedisObj.getUserId(),null,reqBehavior,false);
		return ReturnResult.success(res);
	}
	
	@ApiOperation(value="学习该课程的用户分页查询(前台)")
	@RequestMapping(value="/findLessonClassUser",method = RequestMethod.POST)
	public ReturnResult<Pagination<UserPageDTO>> findLessonClassUser(@Validated @ModelAttribute PageParams pageParams,
																	 HttpServletRequest request){
		LoginRedisObj loginObj = this.getUserObj(request);
		User user = userService.selectByPrimaryKey(loginObj.getUserId());

		Map<String, Object> conditions = new HashMap<>();
		Pagination<UserPageDTO> queryPgn = new Pagination<>();
		conditions.put("classId", user.getClassId());
		conditions.put("type", UserEnums.type.student.getValue());
		conditions.put("isDel", CommEnums.isDel.no.getValue());
		conditions.put("learnStatus", UserEnums.learnStatus.trainning.getValue());
		conditions.put("status", UserEnums.status.normal.getValue());

		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);
		int total = userService.findUserPageCount(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total > 0){
			queryPgn.setTotal(total);
			List<UserPageDTO> list = userService.findUserPageList(queryPgn);
			queryPgn.setList(list);
		}
		return ReturnResult.success(queryPgn);
	}

}
